var formEntityId = "";
var objIds = "";
var entityTypes = "";
var processKey = "";
var readFlag;
$(function() {
	var orgId = $('#orgId').val();
	//增加、编辑及详情页面
	var flag=$("#flag").val();//0详细、1编辑
	if(flag =='0'){
		$('fieldset >div > button').hide();
		$('ul >li > button:last').html(common.i18n('cp.js.u04'));
	}else if(flag =='1'){
		$('ul >li > button:last').html(common.i18n('cp.js.u05'));
	}
	
	//审核
	$("#approve").on("click", function (){
		var ids = $("#grid-pending").bootgrid("getSelectedRows");
		if(ids <=0){
			$.alert(common.i18n('cp.js.p47'));
			return false;
		}else{
			  var confirm_ = confirm(common.i18n('cp.js.sure_to_agree'));
		        if(confirm_){
		            $.ajax({
		                type:"post",
		                url:'flow/' + top.processPath + '/approve?id='+ids,
		                success:function(msg){
		                	common.success(common.i18n('cp.js.operation_successfully')+msg);
		                	location.href='flow/' + top.processPath + '/default';
		                }
		            });
		        }
		}
	});
	$("#queryPending").on("click", function (){
		$("#grid-pending").bootstrapTable('refresh');
	});
	$("#queryDo").on("click", function (){
		$("#grid-do").bootstrapTable('refresh');
	});
	$("#queryParticipate").on("click", function (){
		$("#grid-participate").bootstrapTable('refresh');
	});
	$("#queryTrack").on("click", function (){
		$("#grid-track").bootstrapTable('refresh');
	});
	
	$("#resetPending").on("click", function (){
		$("#queryPendingForm .select2-selection__rendered").html('<span class="select2-selection__placeholder">'+'请选择'+'</span>');
		common.resetForm('queryPendingForm');
	});
	
	$("#resetDo").on("click", function (){
		$("#queryDoForm .select2-selection__rendered").html('<span class="select2-selection__placeholder">'+'请选择'+'</span>');
		common.resetForm('queryDoForm');
	});
	
	$("#resetTrack").on("click", function (){
		$("#queryTrackForm .select2-selection__rendered").html('<span class="select2-selection__placeholder">'+'请选择'+'</span>');
		common.resetForm('queryTrackForm');
	});
	
	$("#resetParticipate").on("click", function (){
		$("#queryParticipateForm .select2-selection__rendered").html('<span class="select2-selection__placeholder">'+'请选择'+'</span>');
		common.resetForm('queryParticipateForm');
	});
	
	$("#viewDo").on("click", function (){
		var ids = $("#grid-do").bootgrid("getSelectedRows");
		var current = $("#grid-do").bootgrid("getSelectedRowsContent");
		var actionName =$(current[0]).prop('actionName');
		if(ids.length > 1|| ids.length ==0){
			$.alert(common.i18n('cp.js.sw07'));
			return false;
		}else {
			if(actionName==""||actionName==null)
				common.addTab('flow/' + top.processPath + '/pdfForm?id='+ids+'&flag=task', '预览');
			else
				common.addTab('flow/'+actionName+'/pdfForm?id='+ids+'&flag=task', '预览');
		}
	});
});
/**
 * 默认的bootstrap-table 行内的操作按钮  | 编辑 | 删除 
 */
function pendingOperate(value, row, index, field) {
	return "<a href=\"javascript:graphView('"+row.instId+"','"+row.taskId+"');\">跟踪流程</a>";
}
function gotoformOperate(value, row, index, field) {
	return link = "<a href=\"javascript: gotoForm('"+row.id+"','"+row.processKey+"','"+row.processName+"','"+row.approver+"');\">"+row.processName+"</a>";
    
}

function gotoForm(id,key,proceeding,approver){
	var linkSize=approver.split('、').length;
	if (approveValid(id,linkSize)){
		common.addTab('/flow/'+key.split("_")[0]+'/gotoForm?taskId='+id, proceeding+'审批');  
	}
}


//流程批量同意
function batchApproveClick(readFlag){
	var rows = $('#grid-pending').bootstrapTable('getSelections');
	if(rows.length<1){
		$.alert("请选中一行数据", "提示");
		return false;
	}
	var ids = new Array();
	var formIds = new Array();
	for(var i=0;i<rows.length;i++){
		var actId =$(rows[i]).prop('taskDefKey');
		var formId = $(rows[i]).prop('formId');
		var taskId = $(rows[i]).prop('id');
		formIds.push(formId);
		ids.push(taskId);
		if(actId=="fqrsq_apply"){
			$.alert('申请人不允许审核，请进入表单点击提交审核！');
			return false;
		}
	}
	var key =$(rows[0]).prop('processKey');
	$.ajax({
		type:"post",
        url: '/flow/baseFlow/batchApproveValid?id='+ids,   
        success:function(res){
        	 common.alert(res, function() {
            	$.ajax({
          			type : "post",
          			url: '/flow/baseFlow/selectAssignee?id='+ids+'&formIds='+formIds+'&key='+key+ '&readFlag=' + readFlag,
          			//data: $("#nodeForm").serialize(), 
          			success : function(data) {
          				$('#assigneeDialog').html(data);
          				$('#assigneeDialog').modal('show');
          				$(".modal-dialog").find("button[data-id='assignee']").on('click', function () {
          	            	var maxHeight = $('.modal-dialog').find('ul').css('max-height');
          	            	maxHeight = parseInt(maxHeight.substring(0,maxHeight.length-2));
          	            	maxHeight+=10;
          	            	$('.modal-dialog').find('ul').parent().css('max-height',maxHeight+'px');
          	            });
          			}
          		});
         	},false);
        }
    });
}

//审批流程表单
function gotoFormClick(){
	var row = $('#grid-pending').bootstrapTable('getSelections');
	if(row.length!=1){
		$.alert("请选中一条数据", "提示");
		return false;
	}
	var current;
	var id =$(row[0]).prop('id');
	var key =$(row[0]).prop('processKey');
	var formId =$(row[0]).prop('formId');
	var approver =$(row[0]).prop('approver');
	var linkSize=0;
	if(approver!=null){
		linkSize=approver.split('、').length;
	}
	if (approveValid(id,linkSize)){//pc端很多地方都要调用了 approveValid 方法（并且optMsg带null或者undefined）。为了区分费用预算提示的要求，optMsg带“”吧 
		common.addTab('/flow/'+key.split("_")[0]+'/gotoForm?taskId='+id+"&formId="+formId, '审批');  
	}
}

//打印功能
function printpage(column, row){
	var current = $("#grid-do").bootgrid("getSelectedRowsContent");
	var ids = $("#grid-do").bootgrid("getSelectedRows");
	var actionName =$(current[0]).prop('actionName');
	if(ids.length <1){
		$.alert(common.i18n('cp.js.prs.789'));
		return false;
	}else if(ids.length >1){
		$.alert(common.i18n('cp.js.prs.792'));
		return false;
	}else{
		var content = current[0].content;
		var formId=current[0].formId;
		if(content==""||content==null){
			var path  = 'flow/'+actionName+'/pdfForm?id='+ids+'&flag=task&pdfFlag=1';
			$.ajax({
				type: "post",  
				url: path,   
				async: false,
				success: function(data) {
					var targetStr = 'class="lc-title02" ><div class="twoBarCode" style="margin-top: -50px;"><img style="height: 100px;width: 100px;" src="flow/images/temp/'+formId+'.png" /></div>';
					data = data.replace('class="lc-title02">',targetStr);
					data = data.replace('class="liucheng tab-pane fade"','class="liucheng"');//表单是多页签时全部显示出来
					document.body.innerHTML = data;
					$('img').load(function(){
						window.print();
						window.location.reload(); 
					});
				}
			});
		}else{
			document.body.innerHTML = content;
			window.print();
			$("#grid-do").bootgrid("search","");
		}
	}
}

function generatePdf(ids,actionName,formId,key){
	var url;var url1;var objId="";
	if(actionName==""||actionName==null){
		url = 'flow/'+ top.processPath + '/pdfForm?id='+ids+"&pdfFlag=1";
		url1 = 'flow/'+ top.processPath + '/generatePdf?id='+ids;
	}
	else{
		url= 'flow/'+actionName+'/pdfForm?id='+ids+"&pdfFlag=1";
		url1= 'flow/'+actionName+'/generatePdf?id='+ids;
	}
	generatePdfMultLanguage(url,url1,formId,'',key/*,queryProcessList*/);
}

function queryProcessList() {
	$("#grid-track").bootgrid("search","");
	$("#grid-participate").bootgrid("search","");
}

function approveValid(taskId,linkSize1){
	var linkSize = linkSize1;
	if(linkSize==undefined && $('#linkSize').length>0)	
		linkSize = $('#linkSize').val();
	var valid = true ;
	$.ajax({
        type:"post",
        url: '/flow/baseFlow/approveValid?linkSize='+linkSize+'&taskId='+taskId,   
        dataType :  'json',
        async: false,
        success:function(data){
        	if(data.code!= 0){
	    		$.alert(data.msg, "提示");
           	 	valid = false;
	       	}
        }
    });
	return valid;
}

function pdfForm(ids,actionName,formId){
	var id=formId;
	if(formId=='' || formId==null || formId==undefined){
		id=ids;
	}
	common.addTab('flow/'+actionName+'/pdfForm?id='+ids+'&flag=inst', '预览'); 
}

//已处理 中撤回流程，针对刚同意，但下个审批节点未审批的流程
function withdrawBackFlow(instId,actionName,formId){
	var url='flow/'+actionName+"/withdrawBackFlow?instId="+instId;
	common.confirm(common.i18n('cp.js.s01'),function(){
		$.ajax({
		      type:"post",
		      url:url,
		      dataType : 'json',
				data: $("#xmlForm").serialize(), 
		      success:function(data){
		      	if(data.code=='true'){
		      		 common.closeModelDialog('assigneeDialog');
		      		 common.success(common.i18n('cp.js.rq22'));
		     		$("#grid-participate").bootgrid("search","");
		      	}else if (data.code == 'false') {
		              $.alert(data.msg);
		          }
		      	enableBtn();
		      }
		  });
	});
}

function query() {
//		timeTask_refresh_pending();//待审
//		resetTrackFormAndQuery();//已发起
//		resetParticipateFormAndQuery();	//已处理
}

function confirmAssignee_pull(){
	var assignee = $('#assignee').val();
	 if(assignee==null||assignee==''||assignee==undefined){
		 $.alert(common.i18n('cp.js.t04'));
			return false;
	 }
	if($('#comment').val().length>4000){
		$.alert(common.i18n('cp.js.alsl'));
		return false;
	}
	disableBtn();
	var userIds = new Array();
	var actionName = $('#actionName').val();
	var ifForceDistribute = $('#ifForceDistribute').val();
	$('.userIds').each(function(index){
		if(userIds.indexOf($(this).val())==-1){
			userIds.push($(this).val());
		}else{
			$('#userId'+index+'Assignee').remove();
			$('#processDelegationId'+index+'Assignee').remove();
			$('#delegateeId'+index+'Assignee').remove();
		}
	});
	assemblyFlowAssigneeVo('batchApprove_pull');
	var url = '/flow/'+ top.processPath + '/batchApprove?msg=Y&ownerCreateType=PULL&userIds='+userIds;
	if(actionName!="")
		url = '/flow/'+actionName+'/batchApprove?msg=Y&ownerCreateType=PULL&userIds='+userIds;
	enableBtn();
	common.confirm('确定审核吗?',function(){
		var id = $('#id').val();
		if(!approveValid(id))return false;
		disableBtn();
	    $.ajax({
	        type:"post",
	        url:url,
	        dataType : 'json',
	        data: $("#batchApproveFormPull").serialize(), 
	        success:function(data){
	        	if(data.code=='true'){
	        		common.closeModelDialog('assigneeDialog');
	        		query();
	        		common.success(common.i18n('cp.js.rq18'),function(){});
	        	}else if (data.code == 'false') {
                    $.alert(common.i18n('cp.js.rq16'));
                }else if (data.code == 'validflag') {
                    $.alert(common.i18n('cp.js.rq16')+"<br/>"+data.msg);
                }
	        	enableBtn();
	        }
	    });	           	
	});
}

function confirmAssignee_jointly(){
	if($('#comment').val().length>4000){
		$.alert('审批意见超长！');
		return false;
	}
	disableBtn();
	var userIds = new Array();
	var positions = new Array()
	var actionName = $('#actionName').val();
	if($('#assignee').prop('disabled')==false){//会签 支持选择场景
		$('#assignee>option').each(function(index){ 
			if($(this).prop("selected")){
				if(userIds.indexOf($(this).val())==-1){
					userIds.push($(this).val());
					positions.push($(this).attr("positionId"));
				}else{
					$('#userId'+index+'Assignee').remove();
					$('#processDelegationId'+index+'Assignee').remove();
					$('#delegateeId'+index+'Assignee').remove();
				}
			}else{
				$('#userId'+index+'Assignee').remove();
				$('#processDelegationId'+index+'Assignee').remove();
				$('#delegateeId'+index+'Assignee').remove();
			} 
		});
	}else{//会签  不支持选择场景
		var assignee=$('#assignee').find('option').eq(0).val();
		$('.userIds').each(function(index){
			if(userIds.indexOf($(this).val())==-1){
				userIds.push($(this).val());
				positions.push($(this).attr("positionId"));
			}else{
				$('#userId'+index+'Assignee').remove();
				$('#processDelegationId'+index+'Assignee').remove();
				$('#delegateeId'+index+'Assignee').remove();
			}
		});
	}
	
	var url = 'flow/'+ top.processPath + '/batchApprove?msg=Y&ownerCreateType=JOINTLY&userIds='+userIds+'&positionIds='+positions;
	if(actionName!="")
		url = 'flow/'+actionName+'/batchApprove?msg=Y&ownerCreateType=JOINTLY&userIds='+userIds+'&positionIds='+positions;
	if($('#assignee').prop('disabled')==true){
		var assignee=$('#assignee').find('option').eq(0).val();
		url=url+"&assignee="+assignee;
	}
	
	assemblyFlowAssigneeVo('batchApprove_jointly');
	enableBtn();
	common.confirm('确定审核吗?',function(){
		if($('#assignee').prop('disabled')==false){//会签 支持选择场景 默认处理人传一个
			$('#assignee').val($('#assignee').find('option:selected').eq(0).val());
		}
		var id = $('#id').val();
		if(!approveValid(id))return false;
		disableBtn();
	    $.ajax({
	        type:"post",
	        url:url,
	        dataType : 'json',
	        data: $("#batchApproveFormJointly").serialize(), 
	        success:function(data){
	        	$('#assignee').attr("disabled", true);
	        	if(data.code=='true'){
	        		common.closeModelDialog('assigneeDialog');
	        		query();
	        		common.success(common.i18n('cp.js.rq18'),function(){});
	        	}else if (data.code == 'false') {
                    $.alert(common.i18n('cp.js.rq16'));
                }else if (data.code == 'validflag') {
                    $.alert(common.i18n('cp.js.rq16')+"<br/>"+data.msg);
                }
	        	enableBtn();
	        }
	    });	           	
	});
}

function disableBtn(){
	$("body").find("input[type='button']").each(function(i){
		$(this).attr("disabled",true);
	});
	$(".assigneeForm").find("button").each(function(i) {
		$(this).attr("disabled", true);
   });
	$('.kj-modal-footer-confirm-btn').attr("disabled", true);
}
 function enableBtn(){
	$("body").find("input[type='button']").each(function(i){
		$(this).removeAttr("disabled");
	 });
	$(".assigneeForm").find("button").each(function(i) {
    	$(this).removeAttr("disabled");
    });
 }
 
 function addNotify(flag,status) {
	    var ids="";
	    if(flag=='track'){ //已发起
	    	 ids = $("#grid-track").bootgrid("getSelectedRows");
	    }else if(flag=='participate'){ //已处理
	    	 ids = $("#grid-participate").bootgrid("getSelectedRows");
	    }else if(flag=='do'){ //知会
	    	var current = $("#grid-do").bootgrid("getSelectedRowsContent");
	    	var ids = new Array();
	    		for(var i=0;i<current.length;i++){
	    			var instId = $(current[i]).prop('instId');
	    			ids.push(instId);
	    		}
	    }if(ids <=0){
			$.alert("请选择需要知会的记录!");
			return false;
		}else{
			$.ajax({
		        type: "post",
		        url: 'flow/baseFlow/addNotifyBatch?instId='+ids+'&flag='+flag,
		        success: function(data) {
		            $('#notifyDialog').html(data);
		            $('#notifyDialog').modal('toggle');
		        }
		    });
		}
	}

//--2020 痛点 流程预览
function graphView(instId,taskId){
	common.addTab('flow/baseFlow/viewFlow?instId='+instId+'&taskId='+taskId, '跟踪流程'); 
}




//状态解析
function showStatus(value, row, index, field){
	if(row.status=='4') return '已退回';
	else if(row.status=='5') return '已撤销';
	else if(row.status=='7') return '已失效';
	else if(row.status=='6') return '已终止';
	else if(row.status=='3') return '已生成';
	else if(row.status=='2') return '已完成';
	else if(row.status=='1') return '审核中';
	else if(!row.endTime) return '审核中';
	else return '已完成';
}

//表单预览
function pdfForm(formId,processKey){
	common.addTab('flow/'+processKey+'/pdfForm?id='+formId, '表单详情',formId); 
}

//已处理操作
function pendingOperateHandled(value, row, index, field) {
	return "<a href=\"javascript:graphView('"+row.instId+"','"+row.taskId+"');\">跟踪流程</a> <a href=\"javascript:pdfForm('"+row.formId+"','"+row.processKey+"');\">预览</a>";
}

//切换tab
function changeTab(tabId){
	$("#"+tabId).show();
	$("#"+tabId).siblings().hide();
}
